<script setup lang="ts">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { memberFeeConfigSaveApi, memberFeeConfigUpdateApi } from '@/api/merchantManagement'
import { memberFeeConfigItem } from '@/api/merchantManagement/types'
import { useValidator } from '@/hooks/web/useValidator'
import { ElMessage } from 'element-plus'

const { required, lengthRange } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => undefined
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const rules = reactive({
  activeCount: [required()],
  memberFee: [required()],
  memberName: [required(), lengthRange({ min: 0, max: 30 })],
  sort: [required()],
  validMonth: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const createUser = async (data: any) => {
  const param: memberFeeConfigItem = {
    activeCount: +data.activeCount,
    memberFee: +data.memberFee,
    memberName: data.memberName,
    originFee: +data.originFee,
    sort: +data.sort,
    validMonth: +data.validMonth
  }
  const res = await memberFeeConfigSaveApi(param)
  return res.code === 200
}

const updateUser = async (data: any) => {
  const param: memberFeeConfigItem = {
    id: data.id,
    activeCount: +data.activeCount,
    memberFee: +data.memberFee,
    memberName: data.memberName,
    originFee: +data.originFee,
    sort: +data.sort,
    validMonth: +data.validMonth,
    showState: data.showState
  }
  const res = await memberFeeConfigUpdateApi(param)
  return res.code === 200
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    if (formData.activeCount > 9999999) {
      ElMessage.error('活动发布次数请勿超过9999999')
      return
    }
    if (formData.sort > 1000000 || formData.sort < 0) {
      ElMessage.error('排序范围为0到1000000之间')
      return
    }
    console.log(formData)
    if (formData.id) {
      // 修改
      return updateUser(formData)
    } else {
      // 新增
      return createUser(formData)
    }
  }
}

// 重置Form
const reset = async () => {
  const elForm = await getElFormExpose()
  setValues({ id: '' })
  elForm?.resetFields()
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  reset,
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
